package com.example.pcbackend.globa;

import com.example.pcbackend.enums.ResultCode;
import com.example.pcbackend.vo.ResultJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


/*    *//**
     * 参数校验错误
     * @param e
     * @return
     *//*
    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResultJson exceptionHandler(ConstraintViolationException e) {

        return ResultJson.failure(ResultCode.BAD_REQUEST,
                e.getConstraintViolations().iterator().next().getMessage());

    }*/

    /**
     * 参数校验错误
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultJson exceptionHandler(MethodArgumentNotValidException e) {

        return ResultJson.failure(ResultCode.BAD_REQUEST,
                e.getBindingResult().getFieldError().getDefaultMessage());

    }

    /**
     * 参数校验错误
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ResultJson exceptionHandler(BindException e) {

        return ResultJson.failure(ResultCode.BAD_REQUEST,
                e.getBindingResult().getFieldError().getDefaultMessage());

    }


    //全局异常
    @ResponseBody
    @ExceptionHandler(value = GlobalException.class)
    public ResultJson exceptionHandler(GlobalException e) {

        if(null == e.getResultCode()){
            return ResultJson.failure();
        }
        return ResultJson.failure(e.getResultCode());
    }


    /**
     * 异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResultJson exceptionHandler(Exception e) {

        e.printStackTrace();
        log.error(e.getMessage());
        //服务器异常
        return ResultJson.failure();

    }
}
